﻿#include "GLLInc.h"

namespace GLL
{

	String Int2Str( __int64 n, int rad )
	{
		char buf [32];
		_i64toa_s(n, buf, 31, rad);
		return buf;
	}

	void String::replace(const String& from, const String& to)
	{
		String::size_type pos = 0;
		String::size_type srcLen = from.size();
		String::size_type desLen = to.size();
		pos=find(from, pos); 
		while ((pos != String::npos))
		{
			std::string::replace(pos, srcLen, to);
			pos=find(from, (pos+desLen));
		}
	}

	String::Vector String::split( const String& delims /*= "\t\n "*/, unsigned int maxSplits /*= 0*/ ) const
	{
		Vector ret;
		// Pre-allocate some space for performance
		ret.reserve(maxSplits ? maxSplits+1 : 10);    // 10 is guessed capacity for most case
		unsigned int numSplits = 0;
		// Use STL methods 
		size_t start, pos;
		start = 0;
		do 
		{
			pos = find_first_of(delims, start);
			if (pos == start)
			{
				// Do nothing
				start = pos + 1;
			}
			else if (pos == String::npos || (maxSplits && numSplits == maxSplits))
			{
				// Copy the rest of the String
				ret.push_back( substr(start) );
				break;
			}
			else
			{
				// Copy up to delimiter
				ret.push_back( substr(start, pos - start) );
				start = pos + 1;
			}
			// parse up to next real data
			start = find_first_not_of(delims, start);
			++numSplits;

		}while (pos != String::npos);

		return ret;
	}

	//-----------------------------------------
	//BM 字符串查找
	//找到c在p中最后匹配的位置,没有就返回－1
	int __fastcall last(const char *p, int length, const char c)
	{
		int count  = 0;
		const char *pp = p + length -1;
		while (pp >= p)
		{
			if (*pp == c) return length - count;
			pp--;
			count++;
		}
		return 0;
	}

	template<typename T> T min(T a, T b)
	{
		if(a < b) return a;
		return b;
	}

	int FindBM(const char *Str, int StrLen, const char *has, int HasLen) 
	{
		if(StrLen == -1) StrLen= strlen((const char*)Str);
		if(HasLen == -1) HasLen= strlen((const char*)has);
		int HasLen_1 = HasLen-1;
		int i = HasLen_1;
		int j = HasLen_1;
		while (i <= StrLen-1)
		{
			if (Str[i]==has[j])
			{
				if (j==0) return i;
				i--;
				j--;
			}else{
				//往后跳，取决于最后一次匹配的字符的位置
				int a = last(has, HasLen, Str[i]);
				i = i + HasLen - min(j, a);
				j = HasLen_1;
			}
		}
		return -1;
	}


};//GLL
